<template>
  <view class="avatar" :class="[`avatar--${shape}`, `avatar--${size}`]">
    <image 
      class="avatar__image" 
      :src="src || defaultAvatar" 
      :mode="mode"
      @error="handleError"
    />
  </view>
</template>

<script setup lang="ts">
import { defineProps, defineEmits, ref } from 'vue'
import { DEFAULT_AVATAR } from '../../constants'

const props = defineProps({
  src: {
    type: String,
    default: ''
  },
  size: {
    type: String,
    default: 'medium',
    validator: (value: string) => ['small', 'medium', 'large'].includes(value)
  },
  shape: {
    type: String,
    default: 'circle',
    validator: (value: string) => ['circle', 'square'].includes(value)
  },
  mode: {
    type: String,
    default: 'aspectFill'
  }
})

const emit = defineEmits(['error'])

// 默认头像
const defaultAvatar = DEFAULT_AVATAR

// 处理图片加载错误
const handleError = (e: any) => {
  emit('error', e)
}
</script>

<style>
.avatar {
  display: inline-block;
  overflow: hidden;
  background-color: #f5f5f5;
}

.avatar__image {
  width: 100%;
  height: 100%;
}

/* 形状 */
.avatar--circle {
  border-radius: 50%;
}

.avatar--square {
  border-radius: 8rpx;
}

/* 尺寸 */
.avatar--small {
  width: 80rpx;
  height: 80rpx;
}

.avatar--medium {
  width: 120rpx;
  height: 120rpx;
}

.avatar--large {
  width: 160rpx;
  height: 160rpx;
}
</style> 